/**
 * 
 */
package cu.ds.logicalsync.fytasrealm.communication;

import java.io.IOException;
import java.util.Date;

import net.jxta.document.MimeMediaType;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.MessageElement;
import net.jxta.endpoint.WireFormatMessage;
import net.jxta.endpoint.WireFormatMessageFactory;
import net.jxta.endpoint.Message.ElementIterator;
import net.jxta.pipe.InputPipe;
import net.jxta.pipe.PipeMsgEvent;
import net.jxta.pipe.PipeMsgListener;
import net.jxta.pipe.PipeService;
import net.jxta.protocol.PipeAdvertisement;
import net.jxta.util.CountingOutputStream;
import net.jxta.util.DevNullOutputStream;

/**
 * @author r.vashira
 *
 */
public class MessageReciever implements PipeMsgListener {

	/** Member Variables **/
	private JxtaConnection connection;
	private InputPipe inputPipe = null;
	
	
	
	/**
	 * Default Constructor
	 * @param connection
	 */
	public MessageReciever(JxtaConnection connection) {
		super();
		this.connection = connection;
	}

	/** Public Methods **/
	
	public void listenBroadcast() {
		try {
            System.out.println("Creating input pipe");
            // Create the InputPipe and register this for message arrival
            // notification call-back
            PipeService pipeService = connection.getPipeService();
            PipeAdvertisement mapPipeAdv = connection.getMapPipeAdvertisement();
            
            inputPipe = pipeService.createInputPipe(mapPipeAdv, this);
        } catch (IOException io) {
            io.printStackTrace();
            return;
        }
        if (inputPipe == null) {
            System.out.println(" cannot open InputPipe");
            System.exit(-1);
        }
        System.out.println("Waiting for msgs on input pipe");
	}
	
	/* (non-Javadoc)
	 * @see net.jxta.pipe.PipeMsgListener#pipeMsgEvent(net.jxta.pipe.PipeMsgEvent)
	 */
	public void pipeMsgEvent(PipeMsgEvent event) {
		Message msg;
        try {
            // Obtain the message from the event
            msg = event.getMessage();
            if (msg == null) {
                System.out.println("Received an empty message");
                return;
            }
            // dump the message content to screen
            printMessageStats(msg, true);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // get all the message elements
        Message.ElementIterator en = msg.getMessageElements();

        if (!en.hasNext()) {
            return;
        }

        // get the message element in the name space PipeClient.MESSAGE_NAME_SPACE
        //MessageElement msgElement = msg.getMessageElement(null, "SimpleBroadcast");
        MessageElement msgElement = msg.getMessageElement(null, "Element1");

        // Get message
        if (msgElement.toString() == null) {
            System.out.println("null msg received");
        } else {
            Date date = new Date(System.currentTimeMillis());
            System.out.println("Message received at :" + date.toString());
            System.out.println("Message content:" + msgElement.toString());
        }
	}

	/** Helper Methods **/
	
	/**
     * Dumps the message content to stdout
     *
     * @param msg     the message
     * @param verbose dumps message element content if true
     */
    public static void printMessageStats(Message msg, boolean verbose) {
        try {
            CountingOutputStream cnt;
            ElementIterator it = msg.getMessageElements();

            System.out.println("------------------Begin Message---------------------");
            WireFormatMessage serialed = WireFormatMessageFactory.toWire(msg, new MimeMediaType("application/x-jxta-msg"), null);

            System.out.println("Message Size :" + serialed.getByteLength());
            while (it.hasNext()) {
                MessageElement el = it.next();
                String eName = el.getElementName();

                cnt = new CountingOutputStream(new DevNullOutputStream());
                el.sendToStream(cnt);
                long size = cnt.getBytesWritten();

                System.out.println("Element " + eName + " : " + size);
                if (verbose) {
                    System.out.println("[" + el + "]");
                }
            }
            System.out.println("-------------------End Message----------------------");
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}
